package com.example.myapplicationndk.js;

import static com.example.myapplicationndk.utils.SPUtil.WEB_HISTORY_SEARCH_RECORD;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;

import com.example.myapplicationndk.FlyApplication;
import com.example.myapplicationndk.R;
import com.example.myapplicationndk.utils.GenerateString;
import com.example.myapplicationndk.utils.SPUtil;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.OnBridgeCallback;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MainJsActivity extends Activity implements OnClickListener {

    private final String TAG = "MainActivity";

    BridgeWebView webView;

    Button button;

    int RESULT_CODE = 0;

    ValueCallback<Uri> mUploadMessage;

    ValueCallback<Uri[]> mUploadMessageArray;
    private Set<String> record = new HashSet<>();//缓存一份记录到本地
    private List<String> historyKeyWord = new ArrayList<>();

    static class Location {
        String address;
    }

    static class User {
        String name;
        Location location;


        String testStr;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_js);

        webView = (BridgeWebView) findViewById(R.id.webView);

        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(this);


        webView.setWebChromeClient(new WebChromeClient() {

            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType, String capture) {
                this.openFileChooser(uploadMsg);
            }

            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType) {
                this.openFileChooser(uploadMsg);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                pickFile();
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                mUploadMessageArray = filePathCallback;
                pickFile();
                return true;
            }
        });


        webView.addJavascriptInterface(new MainJavascriptInterface(webView), "android");
//        webView.setGson(new Gson());

        webView.loadUrl("file:///android_asset/demo.html");
//        webView.loadUrl("https://192.168.203.87:44377/html/demo.html");

        AndroidJs.riginsters(MainJsActivity.this, webView);

        User user = new User();
        Location location = new Location();
        location.address = "SDU";
        user.location = location;
        user.name = "大头鬼";


        getData();


//        webView.callHandler("functionInJs", new Gson().toJson(user), new CallBackFunction() {
//            @Override
//            public void onCallBack(String data) {
//                Log.d(TAG, "onCallBack: " + data);
//            }
//        });

        webView.registerHandler("saveHistory", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.d("saveHistory", data.replace("\"", "").toString());
                saveData(data);
            }
        });

        webView.registerHandler("getData", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.d("getData", data);

                function.onCallBack(historyKeyWord.toString());
            }
        });


        webView.sendToWeb("hello");
    }

    public static String toString(String[] a) {
        if (a == null)
            return "null";
        int iMax = a.length - 1;
        if (iMax == -1)
            return "[]";

        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0; ; i++) {
            b.append(a[i]);
            if (i == iMax)
                return b.append(']').toString();
            b.append(", ");
        }
    }

    private void saveData(String data) {
        data = data.replace("\"", "").toString();
        data = GenerateString.getRandomString(5);
        //record = SPUtil.getInstance().setSpName(FlyApplication.getInstance().getApplicationContext()).getMapString(WEB_HISTORY_SEARCH_RECORD);
        // historyKeyWord
        if (historyKeyWord.size() <= 10) {
            historyKeyWord.add(data);
            for (String key : historyKeyWord) {
                if (!TextUtils.isEmpty(key) && !record.contains(key)) {
                    record.add(key);
                }
            }
            SPUtil.getInstance().setSpName(FlyApplication.getInstance().getApplicationContext()).setMapString(WEB_HISTORY_SEARCH_RECORD, record);
        } else {
            historyKeyWord.set(0, data);
            record.clear();
            for (String key : historyKeyWord) {
                if (!TextUtils.isEmpty(key) && !record.contains(key)) {
                    record.add(key);
                }
            }
            SPUtil.getInstance().setSpName(FlyApplication.getInstance().getApplicationContext()).setMapString(WEB_HISTORY_SEARCH_RECORD, record);
        }
        Log.d("saveHistory", record.toString());

        Log.d("saveHistory1", historyKeyWord.toString());
    }

    private void getData() {
        if (historyKeyWord.size() == 0) {
            record = SPUtil.getInstance().setSpName(FlyApplication.getInstance().getApplicationContext()).getMapString(WEB_HISTORY_SEARCH_RECORD);
            for (String s : record) {
                if (!TextUtils.isEmpty(s)) {
                    if (historyKeyWord.size() == 10) {
                        break;
                    }
                    historyKeyWord.add(s);
                }
            }
        }
        Log.d("saveHistory", "getData");
        Log.d("saveHistory", "getData " + historyKeyWord.toString());
        webView.callHandler("getData", historyKeyWord.toString(), new CallBackFunction() {
            @Override
            public void onCallBack(String data) {
                Log.d("saveHistory", "getData");
                Log.d(TAG, "saveHistory: " + data);
            }
        });

    }


    public void pickFile() {
        Intent chooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
        chooserIntent.setType("image/*");
        startActivityForResult(chooserIntent, RESULT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == RESULT_CODE) {
            if (null == mUploadMessage && null == mUploadMessageArray) {
                return;
            }
            if (null != mUploadMessage && null == mUploadMessageArray) {
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }

            if (null == mUploadMessage && null != mUploadMessageArray) {
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                if (result != null) {
                    mUploadMessageArray.onReceiveValue(new Uri[]{result});
                }
                mUploadMessageArray = null;
            }

        }
    }

    @Override
    public void onClick(View v) {
        if (button.equals(v)) {

            User user = new User();
            Location location = new Location();
            location.address = "SDU";
            user.location = location;
            user.name = "大头鬼";
            webView.callHandler("function", new Gson().toJson(user), new OnBridgeCallback() {

                @Override
                public void onCallBack(String data) {
                    // TODO Auto-generated method stub
                    Log.i(TAG, "reponse from js " + data);
                }

            });
        }

    }

}
